package com.example.myapplication;


import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RatingBar;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import com.example.myapplication.db.DBManager;

public class AddReviewActivity extends AppCompatActivity {
    private EditText editTextReviewer, editTextComment;
    private RatingBar ratingBar;
    private Button buttonSubmit;
    private String courseName;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_review);

        // 设置ActionBar
        if (getSupportActionBar() != null) {
            getSupportActionBar().setTitle("发表评价");
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            getSupportActionBar().setElevation(4);
        }

        // 初始化视图
        editTextReviewer = findViewById(R.id.editTextReviewer);
        editTextComment = findViewById(R.id.editTextComment);
        ratingBar = findViewById(R.id.ratingBar);
        buttonSubmit = findViewById(R.id.buttonSubmit);

        // 获取课程名
        courseName = getIntent().getStringExtra("courseName");

        buttonSubmit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String reviewer = editTextReviewer.getText().toString();
                String comment = editTextComment.getText().toString();
                int rating = (int) ratingBar.getRating();
                if (reviewer.isEmpty() || comment.isEmpty() || courseName == null) {
                    Toast.makeText(AddReviewActivity.this, "请填写完整信息", Toast.LENGTH_SHORT).show();
                    return;
                }
                DBManager dbManager = new DBManager(AddReviewActivity.this);
                // addReview 内部已自动写入当前时间
                dbManager.addReview(courseName, reviewer, rating, comment);
                Toast.makeText(AddReviewActivity.this, "评价已提交", Toast.LENGTH_SHORT).show();
                finish();
            }
        });
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}
